import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/http/base/http_urls.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/app_string.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';

class ZxingPage extends StatefulWidget {
  const ZxingPage({Key key}) : super(key: key);

  @override
  _ZxingPageState createState() => _ZxingPageState();
}

class _ZxingPageState extends State<ZxingPage> {
  GlobalKey repaintKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    UserInfo userInfo = getUserInfo();

    return Scaffold(
      appBar: TopAppBar(context, "我的二维码"),
      body: Container(
        color: AppColor.bg,
        width: MediaQuery.of(context).size.width,
        child: Column(
          children: [
            Center(
              child: RepaintBoundary(
                key: repaintKey,
                child: Container(
                  margin: EdgeInsets.only(top: ScreenUtil().setHeight(50)),
                  width: ScreenUtil().setWidth(345),
                  padding: EdgeInsets.all(ScreenUtil().setWidth(29)),
                  color: Colors.white,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          HeadView(
                              (userInfo.avatar != null &&
                                      userInfo.avatar.isEmpty)
                                  ? HEADER_URL
                                  : userInfo.avatar,
                              ScreenUtil().setWidth(55),
                              ScreenUtil().setWidth(55)),
                          Expanded(
                            flex: 1,
                            child: Padding(
                              padding: const EdgeInsets.only(
                                left: 16.0,
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Text(
                                        userInfo.nickname,
                                        style: TextStyle(
                                            fontSize: sp(16),
                                            color: AppColor.colorDefaultText),
                                      ),
                                      Image.asset(
                                        userInfo.sex == 2
                                            ? AppString.IMAGE_NV
                                            : AppString.IMAGE_NAN,
                                        height: height(12),
                                      )
                                    ],
                                  ),
                                  SizedBox(
                                    height: 4,
                                  ),
                                  Text(
                                    "自语ID：${userInfo.account}",
                                    style: TextStyle(
                                        fontSize: sp(12),
                                        color: AppColor.colorDefaultText),
                                  )
                                ],
                              ),
                            ),
                          )
                        ],
                      ),
                      SizedBox(
                        height: ScreenUtil().setWidth(20),
                      ),
                      QrImage(
                        data: '${HttpUrls.ZXING_CODE}${userInfo.imOpenId}',
                        size: 260,
                      ),
                      Text(
                        AppString.zxingHint,
                        style: TextStyle(
                            color: AppColor.colorGrey153, fontSize: sp(12)),
                      )
                    ],
                  ),
                ),
              ),
            ),
            InkWell(
              onTap: () {
                _saveImage();
              },
              child: Container(
                alignment: Alignment.center,
                margin: EdgeInsets.only(top: 15, bottom: 15, right: 15),
                height: ScreenUtil().setHeight(40),
                width: ScreenUtil().setWidth(100),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: Color.fromRGBO(0, 220, 169, 1),
                ),
                child: Text(
                  "保存至相册",
                  style: TextStyle(
                      color: Colors.white, fontSize: ScreenUtil().setSp(14)),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _saveImage() async {
    await getPerm();
    await capturePng();
  }

  Future getPerm() async {
    // 申请权限
    bool a = await await Permission.storage.request().isGranted;
    print(a);
    if (a == true) {
      print(a);
      print("已经打开");
    } else {
      toast("请打开存储权限");
      await Future.delayed(Duration(seconds: 1));
      print(a);
      openAppSettings();
    }
  }

  Future<String> capturePng() async {
    EasyLoading.show(status: "保存中...");
    try {
      RenderRepaintBoundary boundary =
          repaintKey.currentContext.findRenderObject();
      ui.Image image = await boundary.toImage();
      ByteData byteData =
          await image.toByteData(format: ui.ImageByteFormat.png);
      final result =
          await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
      EasyLoading.dismiss();
      toast("保存成功");
      print(result); // result是图片地址
    } catch (e) {
      print(e);
      toast("保存失败:${e}");
      EasyLoading.dismiss();
    }
    return null;
  }
}
